package com.entrogy.controller;

import com.entrogy.bean.ClassEntity;
import com.entrogy.bean.ClassTypeEntity;
import com.entrogy.bean.PageBean;
import com.entrogy.config.Result;
import com.entrogy.service.ClassService;
import com.entrogy.service.UserService;
import com.entrogy.utils.ApiReturnUtil;
import com.entrogy.utils.DateUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authz.annotation.Logical;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;


@RestController
@RequestMapping(value = "/classcontroller")
@Api(description = "对班级的一些操作")
public class ClassController {


	@Autowired
	private ClassService classService;

	@Autowired
	private UserService userService;

	@ApiOperation(value = "新增年级或班级，从全校到高中部到初中部等等，根据顶级ID去区分.注意：新增年级的时候parentId=0，新增班级的时候把对应的年级ID带过来就行")
	@RequiresPermissions(value = {"class:add", "grade:add"}, logical= Logical.OR)
	@RequestMapping(value = "/insertgrade",method = RequestMethod.POST)
	public Map<String,Object> insertGrade(@ModelAttribute(value="classEntity") ClassEntity classEntity, int schoolCode,Integer gradeId){
		String id="";
		String className="";
		if (classEntity != null) {//
			if (classEntity.getGradeType()!=0){// 获取班级的类型  1高中 2 初中  3 小学 4大学
				if (classEntity.getGradenumber()!=null && !"".equals(classEntity.getGradenumber())){
					int  number=Integer.parseInt(DateUtils.GetNowDate().substring(0,4));
					String m=classEntity.getGradenumber().substring(0,4);
					int  a=number-Integer.parseInt(m);
					if (a > 9) {
						return ApiReturnUtil.error("新增失败，请选择正确的年级");
					}
					//新增年级时
					id = "1" + classEntity.getGradeType() + a + "0000";

					if (classEntity.getGradeType()==1){
						className="高"+m+"级";
					}else if(classEntity.getGradeType()==2){
						className="初"+m+"级";
					}else if(classEntity.getGradeType()==3){
						className="小"+m+"级";
					}else if(classEntity.getGradeType()==4){
						className="大"+m+"级";
					}
				}

			}
			if (classEntity.getClassnumber()!=null && !"".equals(classEntity.getClassnumber())){//获取年级数
				//新增班级时
				if (Integer.parseInt(classEntity.getClassnumber())>99){
					return ApiReturnUtil.error("新增失败，请选择正确的班级");
				}
				String sm="";
				if (Integer.parseInt(classEntity.getClassnumber())<10){
					sm="0"+classEntity.getClassnumber();
				}else{
					sm=classEntity.getClassnumber();
				}
				if (gradeId!=0 && gradeId!=null ){
					classEntity.setParentId(gradeId);
					id=String.valueOf(gradeId).substring(0,3)+sm+"00";
					ClassEntity classEntity1 =classService.getClassById(gradeId,schoolCode);
					className=classEntity1.getClassName()+sm+"班";
				}
			}
		}
		//添加班级时  根据添加的id  查询是否存在
		ClassEntity classEntity1 =classService.getClassById(Integer.parseInt(id),schoolCode);
		if (classEntity1!=null){
			return ApiReturnUtil.error("新增失败，该班级已存在");
		}
		int code = classService.insertGrade(Integer.parseInt(id), className, classEntity.getParentId(),schoolCode);
		if(code == 1){
			return ApiReturnUtil.success("新增成功","");
		}
		return ApiReturnUtil.error("新增失败，请稍后再试");
	}

	@ApiOperation(value = "给老师分配班级（一个老师有多个班级，一个班级被多个老师教.）")
	@ApiImplicitParams({
			@ApiImplicitParam(required = true, paramType = "query", dataType = "int", name = "userId"),
			@ApiImplicitParam(required = true, paramType = "query", dataType = "int", name = "classId")
	})
	@RequestMapping(value = "/insertuserandclass",method = RequestMethod.POST)
	public Map<String,Object> insertUserAndClass(int userId,int classId){
		int code = classService.insertUserAndClass(userId,classId);
		if(code == 1){
			return ApiReturnUtil.success("分配班级成功","");
		}
		return ApiReturnUtil.error("分配班级失败，请稍后再试");
	}

	@ApiOperation(value = "获取所有的班级列表(根据传过来的ID不同，去查询对应的年级或班级信息)如果parentId为空则查询所有的班级信息")
	@ApiImplicitParams({
			@ApiImplicitParam(name = "parentId", dataType = "Integer", paramType = "query", required = false),
			@ApiImplicitParam(name = "schoolCode", dataType = "Integer", paramType = "query", required = false),
			@ApiImplicitParam(name = "className", dataType = "String", paramType = "query", required = false),
			@ApiImplicitParam(name = "currentPage", dataType = "Integer", paramType = "query", required = false),
			@ApiImplicitParam(name = "pageSize", dataType = "Integer", paramType = "query", required = false),
			@ApiImplicitParam(name = "uid", dataType = "String", paramType = "query", required = false),
	})
	@RequestMapping(value = "/getclasslist", method = RequestMethod.GET)
//	@RequiresPermissions(value = {"class:list", "grade:list"},logical= Logical.OR)
	public Result getClassList(Integer parentId, Integer schoolCode, String className, Integer currentPage, Integer pageSize, Integer classType, String uid){
		Map<String,Object> map = new HashMap<>();
		if (className != null && !"".equals(className)){
			map.put("className", className);
		}
		if (currentPage != null && !"".equals(currentPage)){
			map.put("page", (currentPage - 1) * pageSize);
		}
		if (pageSize != null && !"".equals(pageSize)){
			map.put("total", pageSize);
		}
		if (classType != null && !"".equals(classType)){
			map.put("classType", classType);
		}
		if (parentId != null && !"".equals(parentId)){
			map.put("type", 2);
			map.put("parentId", parentId);
		}else{
			map.put("type", 1);
		}
		map.put("schoolCode", schoolCode == null ? userService.getSchoolCodeByUserId(uid) : schoolCode);
		List<ClassEntity> classEntities = classService.getClassList(map);
		int total = classService.getClassListTotal(map);
		return new Result().getResult(401,"查询成功！",1,new PageBean<ClassEntity>().pageBeans(classEntities,total));
	}

	@ApiOperation(value = "根据ID删除班级或年级")
	@RequiresPermissions(value = {"class:delete", "grade:delete"},logical= Logical.OR)
	@ApiImplicitParam(name = "id",dataType = "int",paramType = "query",required = true)
	@RequestMapping(value = "/deleteclass",method = RequestMethod.DELETE)
	public Map<String,Object> deleteClass(int id){
		Integer schoolCode = (Integer) SecurityUtils.getSubject().getSession().getAttribute("schoolCode");
		int code = classService.deleteClass(id, schoolCode);
		if(code == 1){
			return ApiReturnUtil.success("删除成功","");
		}
		return ApiReturnUtil.error("删除失败，请稍后再试");
	}

	@ApiOperation(value = "新增班级类型")
	@RequestMapping(value = "/insertclasstype",method = RequestMethod.POST)
	@RequiresPermissions("classType:add")
	public Map<String,Object> insertClassType(@ModelAttribute(value="classTypeEntity") ClassTypeEntity classTypeEntity,int schoolCode){
		List<ClassTypeEntity> classTypeList = classService.getClassTypeList(schoolCode);
		String classTypeName = classTypeEntity.getTypeName();
		for (ClassTypeEntity typeEntity : classTypeList) {
			if (typeEntity.getTypeName().equals(classTypeName)){
				return ApiReturnUtil.error("新增失败，当中新增的班级类型已存在！");
			}
		}
         int code = classService.insertClassType(classTypeEntity.getTypeName(),schoolCode);
         if(code == 1){
			 return ApiReturnUtil.success("新增成功","");
		 }
		 return ApiReturnUtil.error("新增失败，请稍后再试");
	}

	@ApiOperation(value = "获取班级类型列表")
	@ApiImplicitParam(name = "schoolCode",dataType = "int",paramType = "query",required = true,value = "班级类型名称")
	@RequestMapping(value = "/getclasstypelist",method = RequestMethod.GET)
//	@RequiresPermissions("classType:list")
	public Map<String,Object> getClassTypeList(int schoolCode){
		List<ClassTypeEntity> classTypes = classService.getClassTypeList(schoolCode);
		return ApiReturnUtil.success("获取成功",classTypes);
	}


	@ApiOperation(value = "更新某个班级信息")
	@RequestMapping(value = "/updateclassinfromation",method = RequestMethod.POST)
	@RequiresPermissions("class:update")
	public Map<String,Object> updateClassInformation(@ModelAttribute(value="classEntity") ClassEntity classEntity){
		Integer schoolCode = (Integer) SecurityUtils.getSubject().getSession().getAttribute("schoolCode");
        int code = classService.updateClassInformation(classEntity.getId(),classEntity.getClassTypeId(),classEntity.getClassName(), schoolCode);
        if(code == 1){
			return ApiReturnUtil.success("设置班级的类型成功","");
		}
		return ApiReturnUtil.error("设置班级的类型失败，请稍后再试");
	}

	@ApiOperation(value = "班级类型的删除")
	@ApiImplicitParam(name = "id",dataType = "int",paramType = "query",required = true)
	@RequestMapping(value = "/deleteclasstype",method = RequestMethod.GET)
	@RequiresPermissions("classType:delete")
	public Map<String,Object> deleteClassType(int id){
		int code = classService.deleteClassType(id);
		if(code == 1){
			return ApiReturnUtil.success("删除班级类型成功","");
		}
		return ApiReturnUtil.error("删除班级类型失败，请稍后再试");
	}

	@ApiOperation(value = "获取所有的班级列表(根据传过来的ID不同，去查询对应的年级或班级信息)如果parentId为空则查询所有的班级信息")
	@ApiImplicitParams({
			@ApiImplicitParam(name = "parentId",dataType = "Integer",paramType = "query",required = false),
			@ApiImplicitParam(name = "selectSchoolCode",dataType = "Integer",paramType = "query",required = false),
			@ApiImplicitParam(name = "className",dataType = "String",paramType = "query",required = false),
			@ApiImplicitParam(name = "currentPage",dataType = "Integer",paramType = "query",required = false),
			@ApiImplicitParam(name = "pageSize",dataType = "Integer",paramType = "query",required = false)
	})
	@GetMapping(value = "/listClass")
	public Result listClass(Integer parentId,Integer selectSchoolCode,String className,Integer currentPage, Integer pageSize,Integer  classType){
		Map<String,Object> map = new HashMap<>();
		if (className != null && !"".equals(className)){
			map.put("className",className);
		}
		if (currentPage != null && !"".equals(currentPage)){
			map.put("page",(currentPage-1)*pageSize);
		}
		if (pageSize != null && !"".equals(pageSize)){
			map.put("total",pageSize);
		}
		if (classType != null && !"".equals(classType)){
			map.put("classType",classType);
		}
		if (parentId != null && !"".equals(parentId)){
			map.put("type",2);
			map.put("parentId",parentId);
		}else{
			map.put("type",1);
		}
		map.put("schoolCode", selectSchoolCode);
		List<ClassEntity> classEntities = classService.getClassList(map);
		int total = classService.getClassListTotal(map);
		return new Result().getResult(401, "查询成功！", 1, new PageBean<ClassEntity>().pageBeans(classEntities, total));
	}

}
